<template>
  <div class="activity-member-management">
    <div class="top-bar">
      <div class="activity-info-container">
        <el-descriptions :column="3" border>
          <el-descriptions-item>
            <template #label>
              <div class="custom-label">活动编号</div>
            </template>
            <div class="custom-content">{{ activityInfo.id }}</div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="custom-label">活动名称</div>
            </template>
            <div class="custom-content">{{ activityInfo.activityName }}</div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="custom-label">所属社团</div>
            </template>
            <div class="custom-content">{{ activityInfo.clubName }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="action-bar">
<!--        <div class="search-container">-->
<!--          <el-input-->
<!--            v-model="searchUserId"-->
<!--            placeholder="输入用户编号搜索"-->
<!--            class="search-input"-->
<!--          >-->
<!--            <template #prefix>-->
<!--              <el-icon><Search /></el-icon>-->
<!--            </template>-->
<!--          </el-input>-->
<!--          <el-button @click="handleSearch" type="primary">查询</el-button>-->
<!--        </div>-->
        <el-button type="primary" @click="handleAddMember">添加成员</el-button>
      </div>
    </div>

    <!-- 成员列表 -->
    <el-table :data="paginatedMemberList" class="member-table">
      <el-table-column prop="userId" label="用户编号" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="grade" label="年级" />
      <el-table-column prop="major" label="专业" />
      <el-table-column prop="class" label="班级" />
      <el-table-column prop="contact" label="联系方式" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
            v-if="scope.row.userId !== userStore.id"
            size="small"
            type="danger"
            @click="handleRemoveMember(scope.row)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="确认移除"
    width="30%"
    :before-close="handleClose"
  >
    <span>是否将此成员移出活动？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">否</el-button>
        <el-button type="primary" @click="confirmRemoveMember"> 是 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { useUserStore } from "../../../stores/user";
import {
  ActivityControllerService,
  type ActivityMembershipQueryRequest,
  type ActivityMembershipUpdateRequest,
  AdminActivityControllerService,
  type UserVO,
} from "../../../../generated";
import { useRoute } from "vue-router";

// 定义成员数据结构
interface Member {
  userId: number;
  username: string;
  grade: string;
  major: string;
  class: string;
  contact: string;
}

interface ActivityInfo {
  id: number;
  activityName: string;
  clubName: string;
}

const userStore = useUserStore();
const memberList = ref<Member[]>([]);
const activityInfo = ref<ActivityInfo>({
  id: 0,
  activityName: "",
  clubName: "",
});
const totalItems = ref(0);

const currentPage = ref(1);
const pageSize = ref(10);
const searchUserId = ref("");

const route = useRoute();
const activityIdStr = Number(route.query.activityId);
const activityId = Number(activityIdStr);
const queryRequest = ref<ActivityMembershipQueryRequest>({
  pageSize: 10,
  current: 1,
  activityId: activityId,
});

const loadData = async () => {
  try {
    const membershipRes =
      await ActivityControllerService.listUserVoInActivityByPage(
        queryRequest.value,
      );
    if (membershipRes.code === 0) {
      const userVoList = membershipRes.data?.records as UserVO[];
      memberList.value = userVoList.map(
        (userVO) =>
          ({
            userId: userVO?.id,
            username: userVO?.userName,
            grade: userVO?.grade,
            major: userVO.major,
            class: userVO?.userClass,
            contact: userVO?.phoneNumber,
          }) as Member,
      );
      totalItems.value = memberList.value.length;
    } else {
      memberList.value = [];
      ElMessage.error("加载数据失败：" + (membershipRes.message || "未知错误"));
    }

    const activityRes =
      await ActivityControllerService.getActivityVoById(activityId);
    if (activityRes.code === 0) {
      activityInfo.value = {
        id: activityRes.data?.id as number,
        activityName: activityRes.data?.activityName as string,
        clubName: activityRes.data?.clubVO?.clubName as string,
      };
    } else {
      ElMessage.error("加载数据失败：" + (activityRes.message || "未知错误"));
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    ElMessage.error("加载数据时发生错误，请稍后重试");
  }
};

const paginatedMemberList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return memberList.value.slice(start, end);
});

onMounted(() => {
  loadData();
});

// 搜索处理
const handleSearch = () => {
  queryRequest.value.userId = Number(searchUserId.value);
  queryRequest.value.current = 1;
  currentPage.value = 1;
  loadData();
};

// 页码改变处理
const handlePageChange = (page: number) => {
  currentPage.value = page;
};

// 添加成员方法
const handleAddMember = () => {
  const url = `/manager/activity/member/add?activityId=${activityId}`;
  window.open(url, "_blank");
};

// 移除成员方法
const dialogVisible = ref(false);
const deleteUserId = ref(0);

const handleRemoveMember = (member: Member) => {
  deleteUserId.value = member.userId;
  dialogVisible.value = true;
};

// 添加确认移除成员的函数
const confirmRemoveMember = async () => {
  try {
    const request = {
      userId: deleteUserId.value,
      activityId: activityId,
    } as ActivityMembershipUpdateRequest;
    const res =
      await AdminActivityControllerService.deleteMemberFromActivity(request);

    if (res.code === 0) {
      ElMessage.success("成员已成功移除");
      // 重新加载数据
      await loadData();
    } else {
      ElMessage.error("移除成员失败：" + res.message);
    }
  } catch (error) {
    ElMessage.error("移除成员时发生错误");
  } finally {
    dialogVisible.value = false;
  }
};

// 添加关闭对话框的处理函数
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确认关闭？")
    .then(() => {
      done();
    })
    .catch(() => {
      // 取消关闭
    });
};
</script>
<style scoped>
.activity-member-management {
  padding: 20px;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.activity-info-container {
  flex: 0 0 auto;
  margin-right: 20px;
}

.action-bar {
  display: flex;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.search-input {
  width: 200px;
  margin-right: 10px;
}

.member-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}
</style>
